package cn.zy.management;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Set;

import javax.imageio.ImageIO;

public class PaintUtil {

	public PaintUtil() {
		image = new BufferedImage(this.WIDTH, this.HEIGHT, BufferedImage.TYPE_INT_RGB);
		graphics = (Graphics2D)image.getGraphics();
		graphics.setBackground(Color.WHITE);  
        graphics.clearRect(0, 0, WIDTH, HEIGHT);    
        graphics.setPaint(Color.BLACK);  
	}
	
	public void paintName(String name, int index) throws IOException {
		int left = LEFT;
		int top = TOP + 3 * index * RADIUS;
		int width = 2 * RADIUS;
		int height = 2 * RADIUS;
		
		graphics.drawOval(left, top, width, height);
		graphics.drawString(name, left, top);
		save();
	}
	
	public void paintIP(String ipAddress, int index) throws IOException {
		int left = LEFT + DISTANCE;
		int top = TOP + 3 * index * RADIUS;
		int width = 2 * RADIUS;
		int height = 2 * RADIUS;
		
		graphics.drawOval(left, top, width, height);
		graphics.drawString(ipAddress, left, top);
		save();
	}
	
	public void paintRelation(String name, String ip, int nameIndex, int ipIndex) throws IOException {
		int left = LEFT + RADIUS;
		int top = TOP + 3 * nameIndex * RADIUS + RADIUS;
		int right = LEFT + DISTANCE + RADIUS;
		int bottom = TOP + 3 * ipIndex * RADIUS + RADIUS;
		
		graphics.drawLine(left, top, right, bottom);
		save();
	}
	
	public void paintAll(StringPair pair) throws IOException {
		Set<String> nameSet = pair.getFirstListSet();
		Set<String> ipSet = pair.getSecondListSet();
		
		String[] names = nameSet.toArray(new String[]{});
		String[] ips = ipSet.toArray(new String[]{});
		
		for(int i = 0; i < names.length; i++) {
			paintName(names[i], i);
			for(int j = 0; j < ips.length; j++) {
				paintIP(ips[j], j);
				
				if (pair.contains(names[i], ips[j])) {
					paintRelation(names[i], ips[j], i, j);
				}
			}
		}
	}
	
	private void save() throws IOException {
		File f = new File(dir);
		ImageIO.write(image, "jpg", f);
	}
	
	private String dir = "D:\\test.jpg";
	private Graphics2D graphics;
	private BufferedImage image;
	
	private final int WIDTH = 200;
	private final int HEIGHT = 600;
	
	private final int TOP = 20;
	private final int LEFT = 20;
	
	private final int RADIUS = 20;
	private final int DISTANCE = 100;
}
